<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="时间范围">
              <el-date-picker v-model="timeRange" type="datetimerange" range-separator="至" start-placeholder="开始时间"
                end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"
                @change="handleTimeRangeChange" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="报表状态">
              <el-select v-model="queryParams.reportStatus" placeholder="请选择报表状态" clearable style="width: 100%">
                <el-option label="待提交" value="1" />
                <el-option label="待审核" value="2" />
                <el-option label="已处理" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="text-align: left;">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
            <el-button type="success" @click="handleExport">
              <el-icon class="el-icon--left">
                <Download />
              </el-icon>
              导出
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="mt-2">
      <el-table :data="reportList" border v-loading="loading" @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center" />
        <el-table-column prop="reportNumber" label="报表编号" align="center" />
        <el-table-column prop="reportType" label="报表类型" align="center" />
        <el-table-column prop="reportGenerateTime" label="生成时间" align="center" />
        <el-table-column prop="reportStatus" label="报表状态" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.reportStatus)">
              {{ getStatusLabel(row.reportStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="submitTime" label="提交时间" align="center" />
        <el-table-column prop="reviewTime" label="审核时间" align="center" />
        <el-table-column prop="exportCount" label="导出次数" align="center" />
        <el-table-column label="操作" width="350" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleAdjust(row)" v-if="row.reportStatus === '1'">
              补调
            </el-button>
            <el-button size="small" type="success" @click="handleCommit(row)" v-if="row.reportStatus === '1'">
              提交
            </el-button>
            <el-button size="small" type="warning" @click="handleReview(row)" v-if="row.reportStatus === '2'">
              审核
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)" v-if="row.reportStatus === '1'">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination class="mt-2" background layout="total, sizes, prev, pager, next, jumper" :total="total"
        v-model:page-size="queryParams.pageSize" v-model:current-page="queryParams.pageNum"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialog.visible" :title="`报表详情 - ${detailDialog.data.reportNumber}`" width="800px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="报表类型">{{ detailDialog.data.reportType }}</el-descriptions-item>
        <el-descriptions-item label="生成时间">{{ detailDialog.data.reportGenerateTime }}</el-descriptions-item>
        <el-descriptions-item label="报表状态">
          <el-tag :type="getStatusTagType(detailDialog.data.reportStatus)">
            {{ getStatusLabel(detailDialog.data.reportStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="提交时间">{{ detailDialog.data.submitTime || '未提交' }}</el-descriptions-item>
        <el-descriptions-item label="审核时间">{{ detailDialog.data.reviewTime || '未审核' }}</el-descriptions-item>
        <el-descriptions-item label="导出次数">{{ detailDialog.data.exportCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="上次导出时间">{{ detailDialog.data.lastExportTime || '未导出' }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ detailDialog.data.creator }}</el-descriptions-item>
        <el-descriptions-item label="数据补调日志">
          <pre>{{ detailDialog.data.dataAdjustmentLog || '无' }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="审核意见">
          <pre>{{ detailDialog.data.reviewComments || '无' }}</pre>
        </el-descriptions-item>
      </el-descriptions>
      <el-divider content-position="left">报表数据</el-divider>
      <pre class="report-data">{{ detailDialog.data.reportData }}</pre>
      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 数据补调对话框 -->
    <el-dialog v-model="adjustDialog.visible" title="数据补调" width="600px" :close-on-click-modal="false">
      <el-form ref="adjustFormRef" :model="adjustForm" :rules="adjustRules" label-width="100px">
        <el-form-item label="补调数据" prop="reportData">
          <el-input v-model="adjustForm.reportData" type="textarea" :rows="6" placeholder="请输入补调数据" />
        </el-form-item>
        <el-form-item label="补调说明" prop="dataAdjustmentLog">
          <el-input v-model="adjustForm.dataAdjustmentLog" type="textarea" :rows="3" placeholder="请输入补调说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="adjustDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitAdjust">保存</el-button>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog v-model="reviewDialog.visible" title="报表审核" width="600px" :close-on-click-modal="false">
      <el-form ref="reviewFormRef" :model="reviewForm" :rules="reviewRules" label-width="100px">
        <!-- <el-form-item label="报表编号">
          <el-input v-model="reviewForm.reportNumber" disabled />
        </el-form-item> -->
        <!-- <el-form-item label="审核结果" prop="reviewResult">
          <el-radio-group v-model="reviewForm.reviewResult">
            <el-radio label="approve">通过</el-radio>
            <el-radio label="reject">拒绝</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="审核意见" prop="reviewComments">
          <el-input v-model="reviewForm.reviewComments" type="textarea" :rows="3" placeholder="请输入审核意见" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="reviewDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitReview">提交审核</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  listProRunReports,
  getProRunReportDetail,
  deleteProRunReports,
  adjustReportData,
  commitReport,
  reviewReport
} from '@/api/prod_operate/prod_run/run_report'
const { proxy } = getCurrentInstance();

// 时间范围选择器数据
const timeRange = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  startTime: '',
  endTime: '',
  reportStatus: ''
})

// 表单数据
const adjustForm = reactive({
  id: undefined,
  reportNumber: '',
  reportData: '',
  dataAdjustmentLog: ''
})

const reviewForm = reactive({
  id: undefined,
  reportNumber: '',
  reviewResult: 'approve',
  reviewComments: ''
})

// 对话框控制
const detailDialog = reactive({
  visible: false,
  data: {}
})

const adjustDialog = reactive({
  visible: false
})

const reviewDialog = reactive({
  visible: false
})

// 表格数据
const reportList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref([])
const adjustFormRef = ref()
const reviewFormRef = ref()

// 表单验证规则
const adjustRules = reactive({
  reportData: [
    { required: true, message: '请输入补调数据', trigger: 'blur' }
  ],
  dataAdjustmentLog: [
    { required: true, message: '请输入补调说明', trigger: 'blur' }
  ]
})

const reviewRules = reactive({
  // reviewResult: [
  //   { required: true, message: '请选择审核结果', trigger: 'change' }
  // ],
  reviewComments: [
    { required: true, message: '请输入审核意见', trigger: 'blur' }
  ]
})

// 处理时间范围变化
const handleTimeRangeChange = (val) => {
  if (val && val.length === 2) {
    queryParams.startTime = val[0]
    queryParams.endTime = val[1]
  } else {
    queryParams.startTime = ''
    queryParams.endTime = ''
  }
}
// 导出数据
async function handleExport() {
  try {
    proxy.download("/operation/web/operationProRunReportForms/export", queryParams, `user_${new Date().getTime()}.xlsx`);
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const map = {
    '1': 'warning', // 待提交
    '2': 'info',    // 待审核
    '3': 'success'  // 已处理
  }
  return map[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const map = {
    '1': '待提交',
    '2': '待审核',
    '3': '已处理'
  }
  return map[status] || '未知状态'
}

// 获取报表列表
const fetchReportList = async () => {
  try {
    loading.value = true
    const res = await listProRunReports(queryParams)
    reportList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取报表列表失败:', error)
    ElMessage.error('获取报表列表失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchReportList()
}

// 重置查询
const resetQuery = () => {
  queryParams.pageNum = 1
  queryParams.startTime = ''
  queryParams.endTime = ''
  queryParams.reportStatus = ''
  timeRange.value = []
  fetchReportList()
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  fetchReportList()
}

// 当前页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  fetchReportList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 查看详情
const handleView = async (row) => {
  try {
    const res = await getProRunReportDetail(row.id)
    detailDialog.data = res.data
    detailDialog.visible = true
  } catch (error) {
    console.error('获取报表详情失败:', error)
    ElMessage.error('获取报表详情失败')
  }
}

// 数据补调
const handleAdjust = (row) => {
  Object.assign(adjustForm, {
    id: row.id,
    reportNumber: row.reportNumber,
    reportData: row.reportData,
    dataAdjustmentLog: row.dataAdjustmentLog
  })
  adjustDialog.visible = true
}

// 提交补调数据
const submitAdjust = async () => {
  try {
    await adjustFormRef.value.validate()
    await adjustReportData(adjustForm)
    ElMessage.success('补调成功')
    adjustDialog.visible = false
    fetchReportList()
  } catch (error) {
    console.error('补调失败:', error)
  }
}

// 提交报表
const handleCommit = (row) => {
  ElMessageBox.confirm(`确认提交报表 "${row.reportNumber}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return commitReport(row.id)
  }).then(() => {
    ElMessage.success('提交成功')
    fetchReportList()
  }).catch(() => { })
}

// 审核报表
const handleReview = (row) => {
  Object.assign(reviewForm, {
    id: row.id,
    reportNumber: row.reportNumber,
    reviewResult: 'approve',
    reviewComments: ''
  })
  reviewDialog.visible = true
}

// 提交审核
const submitReview = async () => {
  try {
    await reviewFormRef.value.validate()

    const data = {
      id: reviewForm.id,
      reviewResult: reviewForm.reviewResult,
      reviewComments: reviewForm.reviewComments
    }

    await reviewReport(data)
    ElMessage.success('审核提交成功')
    reviewDialog.visible = false
    fetchReportList()
  } catch (error) {
    console.error('审核提交失败:', error)
  }
}

// 删除报表
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除报表 "${row.reportNumber}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return deleteProRunReports([row.id])
  }).then(() => {
    ElMessage.success('删除成功')
    fetchReportList()
  }).catch(() => { })
}

// 初始化加载数据
onMounted(() => {
  fetchReportList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.mt-2 {
  margin-top: 20px;
}

.report-data {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  white-space: pre-wrap;
  word-break: break-all;
}

/* 表格列宽自适应 */
:deep(.el-table) {
  width: 100%;
}

:deep(.el-table__cell) {
  padding: 12px 0;
}
</style>